package control;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.PrintStream;

import model.acs.AntGraph;
import model.acs.qprs.AntColony4QPRS;

public class RandomACS {
	private int nAnts;
	private int nNodes;
	private int nIterations;
	private int nRepetitions; 
	private static PrintStream acsOuts;
	
	public RandomACS() {
		nAnts = 100;
		nNodes = -1;
		nIterations = 50;
		nRepetitions = 1; 		
	}
	
	public RandomACS(int nAnts, int nNodes, int nIterations, int nRepetitions) {
		this.nAnts = nAnts;
		this.nNodes = nNodes;
		this.nIterations = nIterations;
		this.nRepetitions = nRepetitions; 		
	}	

	public void bashRunACS(){
		double d[][] = null;
		int t[] = null;
		try {
			acsOuts = new PrintStream(new FileOutputStream(Config.workDir + "test_results.csv"));
			acsOuts.println("Id,Ants,Tree_Nodes,Iterations,Path,Time(s),Distance,Path_Nodes");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}		
		
		for(int i = 0; i < RandomGraph.getNumberOfGaphs(); i++){
			try {     
				// Rotina de leitura do resultado do QuadTree			
				ObjectInputStream ins = new ObjectInputStream(new FileInputStream(Config.workDir + i + "_random_graph.bin"));
				d = (double[][])ins.readObject();
				ins.close();
				ins = new ObjectInputStream(new FileInputStream(Config.workDir + i + "_random_target.bin"));
				t = (int[])ins.readObject();
			} catch(Exception ex) {
				ex.printStackTrace();
			}
			runAntColonySystem(d, t, i);
		}
	}	
	
	private void runAntColonySystem(double[][] deltas, int[] targets, int id){
		System.out.println("Running AntColonySystem for QPRS for Graph " + id);              

		double d[][] = deltas;

		nNodes = d.length;	
		AntGraph graph = new AntGraph(nNodes, d);
		
		int nNodesInZArray[] = targets;
		
		for(int i = 0; i < nRepetitions; i++)
		{
			AntColony4QPRS antColony = new AntColony4QPRS(graph, nNodesInZArray, nAnts, nIterations);
			long time = System.currentTimeMillis();
			antColony.start();
			time = System.currentTimeMillis() - time;
			if(antColony.getBestPath()!=null){
				System.out.println("Best path found for test " + (id+1) + " in round " + (i+1));
				String path = "";
				for(int k = 0; k < antColony.getBestPath().length; k++)
					path += antColony.getBestPath()[k] + " ";
				acsOuts.println((id+1) + "," + nAnts + "," + nNodes + "," + nIterations + "," + path + "," + (time/1000) + "," + antColony.getBestPathValue() + "," + antColony.getBestPath().length);
			}
			else System.out.println("There's no path from "+nNodesInZArray[0]+" to "+nNodesInZArray[1] + "\n");
			graph.resetTau();
		}		
	}	
}
